package com.platform.api.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.platform.api.config.mini.KsMiniApp;
import com.platform.common.core.Constant;
import com.platform.common.core.Result;
import com.platform.common.util.http.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author guoyunfei on 2021/11/23 17:13
 * @className DouyinService
 * @description TODO
 * @Version 1.0
 */


@Service
@Slf4j
public class KsService {


    @Autowired
    private KsMiniApp ksMiniApp;


    /**
     * 快手授权登录
     * @return
     */
    public Result loginForKs(String js_code) throws IOException {
        if (StringUtils.isEmpty(js_code) ) {
            return Result.failure("js_code 不能为空");
        }
        Map<String,String> param = new HashMap<>();
        param.put("app_id", ksMiniApp.getAppid());
        param.put("app_secret", ksMiniApp.getSecret());
        param.put("js_code", js_code);

        String baseDataStr = HttpClientUtil.doPost(Constant.KS_LOGIN_URL, param);
        //{"result":1,"session_key":"pV8Z9KgKDq0RC2q3/dX3tA==","open_id":"f197d432e2b116b514bf57248f3688b2"}
        log.info(baseDataStr);
        JSONObject jsonObject = JSON.parseObject(baseDataStr);
        if(jsonObject.getIntValue("result") == 1){

            return Result.success(jsonObject.getString("open_id"));
        }

        return Result.failure("登录失败");
    }

}
